/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package net.worlds.object;

import java.util.ArrayList;
import net.worlds.WorldsException;
import org.jbox2d.common.Vec2D;
import se.krka.kahlua.vm.JavaFunction;
import se.krka.kahlua.vm.LuaCallFrame;
import se.krka.kahlua.vm.LuaTableImpl;


public class SpawnManager extends GameObject{
    private ArrayList<Part> spawnParts = new ArrayList<Part>(16);
    public SpawnManager() throws WorldsException
    {
        super("SpawnManager");
        explorable = false;
        addFunction("getSpawn", new JavaFunction()
        {

            public int call(LuaCallFrame callFrame, int nArguments) {
                callFrame.push(getSpawn());
                return 1;
            }
        });
        addFunction("getAllSpawnParts", new JavaFunction()
        {
            @Override
            public int call(LuaCallFrame callFrame, int nArguments) {
                LuaTableImpl t = new LuaTableImpl();
                for(int i = 0; i < spawnParts.size(); i++)
                    t.rawset(i+1, spawnParts.get(i));
                callFrame.push(t);
                return 1;
            }
        });
        //x_;
    }
    public void addSpawn(Part p)
    {
        if(!spawnParts.contains(p))
            spawnParts.add(p);
    }
    public void removeSpawn(Part p)
    {
        if(spawnParts.contains(p))
            spawnParts.remove(p);
    }
    public Vec2D getSpawn()
    {
        if(spawnParts.size() == 0)
            return new Vec2D(world.getWidth()/2, world.getHeight()/2);
        else
        {
            int r = (int) Math.round(Math.random() * (spawnParts.size() - 1));
            return spawnParts.get(r).getPosition();
        }
    }
}
